const util = require('util');
const debug = util.debuglog('oil-game:login:cache');
const { 
  Constant,
  SMS_OVERTIME,
} = require('./consts')

//获取当前用户
exports.getUserInfo = async function(uid){
  let user = this.app.loginService.getUser(uid);
  return user;
}

//设置用户联系方式
exports.updateContactInfo = async function(uid, contact_info){
  let user = this.app.loginService.getUser(uid);
  user.contact_info = contact_info;
}

//从redis中验证查询验证码
exports.checkUserCode = function(uid, code){
  let redis = this.app.get("redis");
  let key = Constant.SMS + uid;
  debug("从redis中查询手机验证码 uid = %s 验证码 = %s 存储到redis中，键为 %s", uid, code, key);
  return new Promise((resolve, reject) => {
    redis.get(key, function (err, data) {;
      if(err) return reject(err);
      resolve(code == data);
    });
  });
}

//存储手机验证码到redis中
exports.saveUserCode = function(uid, code){
  let key = Constant.SMS + uid;
  debug("将 uid = %s 验证码 = %s 存储到redis中，键为 %s", uid, code, key);

  return new Promise((resolve, reject) => {
    let redis = this.app.get("redis");
    redis.set(key, code, function(err, data){   //设置倒计时键
      if(err){ 
        debug("将 uid = %s 验证码 = %s 存储到redis中，键为 %s，存储时发生异常 %s", uid, code, key, err);
        return reject(err);
      }
      redis.expire(key, SMS_OVERTIME, function(err, data){    //倒计时键设置超时
        if(err){ 
          debug("将 uid = %s 验证码 = %s 存储到redis中，键为 %s，设置超时时发生异常 %s", uid, code, key, err);
          return reject(err);
        }
        resolve(data);
      });
    });
  });
}
